/**
 * Created by xesam[416249980@qq.com] on 14-11-5.
 */
if (window.bmap) {
    throw "namespace confilct";
}

function extend(Child, Parent) {
    var F = function () {
    };
    F.prototype = Parent.prototype;
    Child.prototype = new F();
    Child.prototype.constructor = Child;
    Child.superclass = Parent.prototype;
}


function BmapLayer() {
    var _this = this;
    this.listners = {};
    this.wrapClickListener = function (event) {
        if (_this.clickListner) {
            _this.clickListner(event);
        }
    };
    this.wrapDbClickListener = function (event) {
        if (_this.dbclickListner) {
            _this.dbclickListner(event);
        }
    };
}

BmapLayer.prototype = {
    constructor: BmapLayer,
    'inflate': function () {
        this.markers = [];
        for (var i = 0, size = this.adapter.getCount(); i < size; i++) {
            var marker = this.adapter.getItem(i);
            marker.index = i;
            this.markers.push(marker);
        }
    },
    'addToMap': function (bmap) {
        this.inflate();
        for (var i = 0, size = this.markers.length; i < size; i++) {
            var marker = this.markers[i];
            for (var eventName in this.listners) {
                marker.addEventListener(eventName, this.listners[eventName]);
            }
            map.addOverlay(marker);
        }
    },
    'removeFromMap': function (bmap) {
        for (var i = 0, size = this.markers.length; i < size; i++) {
            var marker = this.markers[i];
            for (var eventName in this.listners) {
                marker.removeEventListener(this.listners[eventName]);
            }
            map.removeOverlay(marker);
        }
    },
    'setAdapter': function (adapter) {
        this.adapter = adapter;
        return this;
    },
    'click': function (l) {
        this.addEventListner('click', l);
        return this;
    },
    'addEventListner': function (eventName, fn) {
        this.listners[eventName] = function (event) {
            fn(event);
        };
        return this;
    }
};

function BmapLayerAdatper(data) {
    this.data = data;
}

BmapLayerAdatper.prototype = {
    constructor: BmapLayerAdatper,
    'getItem': function (index) {
        var item = this.data[index];
        var point = new BMap.Point(item['lng'], item['lat']);
        var marker = new BMap.Marker(point);
        return marker;
    },

    'getCount': function () {
        return this.data.length;
    }
};

